package io.seata.sample.service;

import io.seata.sample.dao.AccountDao;
import io.seata.sample.entity.Account;
import io.seata.sample.feign.OrderApi;
import java.math.BigDecimal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author IT云清
 */
@Service("accountServiceImpl")
public class AccountServiceImpl implements AccountService{

    private static final Logger LOGGER = LoggerFactory.getLogger(AccountServiceImpl.class);

    @Autowired
    private AccountDao accountDao;

    @Autowired
    private OrderApi orderApi;

    /**
     * 扣减账户余额
     * @param userId 用户id
     * @param money 金额
     * @param orderId
     */
    @Override
    public void decrease(Long userId, BigDecimal money, Long orderId) {
        LOGGER.info("------->扣减账户开始account中");
        //模拟超时异常，全局事务回滚
       /* try {
            Thread.sleep(30*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        Account account = accountDao.selectById(userId);
        if (null == account) {
            LOGGER.info("------->用户不存在 userId={}", userId);
            throw new RuntimeException("用户不存在");
        }
        BigDecimal total = account.getTotal();
        BigDecimal used = account.getUsed();
        BigDecimal yuHe = total.subtract(used);
        if (money.compareTo(yuHe) > 0) {
            LOGGER.info("------->用户[{}]余额不足 total={} used={} yuHe={} price={}", userId, total, used, yuHe, money);
            throw new RuntimeException("余额不足");
        }
        accountDao.decrease(userId,money);
        LOGGER.info("------->扣减账户结束account中");

        //修改订单状态，此调用会导致调用成环
        LOGGER.info("修改订单状态开始");
        String mes = orderApi.update(userId, money.multiply(new BigDecimal("0.09")),0,orderId);
        LOGGER.info("修改订单状态结束：{}",mes);
    }
}
